<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>代码分析 - AI Worker</title>
    <!-- Marked.js for Markdown rendering -->
    <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
    <!-- Highlight.js for code syntax highlighting -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/github.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 30px 20px;
        }

        .container {
            max-width: 1400px;
            margin: 0 auto;
        }

        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            color: white;
        }

        .header h1 {
            font-size: 2em;
        }

        .btn-back {
            background: rgba(255,255,255,0.2);
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s;
        }

        .btn-back:hover {
            background: rgba(255,255,255,0.3);
        }

        .panel {
            background: white;
            border-radius: 15px;
            padding: 30px;
            margin-bottom: 20px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
        }

        .panel-title {
            font-size: 1.4em;
            color: #333;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 2px solid #e9ecef;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #333;
        }

        .form-group select,
        .form-group input[type="text"] {
            width: 100%;
            padding: 12px;
            border: 2px solid #dee2e6;
            border-radius: 8px;
            font-size: 1em;
            transition: border-color 0.3s;
        }

        .form-group select:focus,
        .form-group input:focus {
            outline: none;
            border-color: #667eea;
        }

        .help-text {
            font-size: 0.9em;
            color: #666;
            margin-top: 5px;
        }

        .btn {
            padding: 12px 24px;
            border: none;
            border-radius: 8px;
            font-size: 1em;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
        }

        .btn-primary {
            background: #667eea;
            color: white;
        }

        .btn-success {
            background: #28a745;
            color: white;
        }

        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0,0,0,0.2);
        }

        .btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }

        .analysis-list {
            display: flex;
            flex-direction: column;
            gap: 15px;
        }

        .analysis-item {
            background: #f8f9fa;
            padding: 25px;
            border-radius: 10px;
            border-left: 4px solid #764ba2;
        }

        .analysis-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }

        .analysis-title {
            font-size: 1.1em;
            font-weight: 600;
            color: #333;
        }

        .analysis-meta {
            color: #666;
            font-size: 0.9em;
            margin-bottom: 15px;
            line-height: 1.6;
        }

        .analysis-content {
            background: white;
            padding: 20px;
            border-radius: 8px;
            white-space: pre-wrap;
            max-height: 400px;
            overflow-y: auto;
            color: #333;
            line-height: 1.6;
        }

        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #999;
        }

        .empty-state-icon {
            font-size: 3em;
            margin-bottom: 15px;
        }

        .message {
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            display: none;
        }

        .message.show {
            display: block;
        }

        .message.error {
            background: #f8d7da;
            color: #721c24;
            border-left: 4px solid #dc3545;
        }

        .message.success {
            background: #d4edda;
            color: #155724;
            border-left: 4px solid #28a745;
        }

        .loading {
            text-align: center;
            padding: 40px;
            color: #999;
        }

        .spinner {
            border: 4px solid #f3f3f3;
            border-top: 4px solid #667eea;
            border-radius: 50%;
            width: 50px;
            height: 50px;
            animation: spin 1s linear infinite;
            margin: 0 auto 20px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .project-buttons {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
            gap: 12px;
            margin-top: 10px;
        }

        .project-btn {
            padding: 15px 20px;
            border: 2px solid #dee2e6;
            border-radius: 10px;
            background: white;
            cursor: pointer;
            transition: all 0.3s;
            text-align: left;
        }

        .project-btn:hover {
            border-color: #667eea;
            background: #f8f9fa;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        }

        .project-btn.selected {
            border-color: #667eea;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }

        .project-btn-name {
            font-weight: 600;
            font-size: 1.1em;
            margin-bottom: 5px;
        }

        .project-btn-branch {
            font-size: 0.9em;
            opacity: 0.8;
        }

        .project-btn-repo {
            font-size: 0.85em;
            opacity: 0.7;
            margin-top: 5px;
            word-break: break-all;
        }

        /* AI模型选择样式 */
        .model-buttons {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
            gap: 12px;
            margin-top: 10px;
        }

        .model-btn {
            padding: 15px 20px;
            border: 2px solid #dee2e6;
            border-radius: 10px;
            background: white;
            cursor: pointer;
            transition: all 0.3s;
            text-align: left;
        }

        .model-btn:hover {
            border-color: #667eea;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.2);
        }

        .model-btn.selected {
            border-color: #667eea;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }

        .model-name {
            font-weight: 600;
            margin-bottom: 5px;
            font-size: 1.1em;
        }

        .model-info {
            font-size: 0.85em;
            margin-top: 4px;
            opacity: 0.8;
        }

        .model-badge {
            display: inline-block;
            padding: 3px 8px;
            background: #e9ecef;
            color: #666;
            border-radius: 12px;
            font-size: 0.75em;
            margin-top: 8px;
        }

        .model-btn.selected .model-badge {
            background: rgba(255, 255, 255, 0.3);
            color: white;
        }

        /* MR地址输入框样式 */
        .mr-input-wrapper {
            position: relative;
            margin-bottom: 10px;
        }

        .mr-input-wrapper input {
            padding-right: 40px;
        }

        .mr-remove-btn {
            position: absolute;
            right: 10px;
            top: 50%;
            transform: translateY(-50%);
            background: #dc3545;
            color: white;
            border: none;
            border-radius: 50%;
            width: 28px;
            height: 28px;
            cursor: pointer;
            font-size: 1.2em;
            line-height: 1;
            transition: all 0.3s;
        }

        .mr-remove-btn:hover {
            background: #c82333;
        }

        .btn-add-mr {
            background: #28a745;
            color: white;
            padding: 8px 16px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 0.9em;
            transition: all 0.3s;
            margin-top: 8px;
        }

        .btn-add-mr:hover {
            background: #218838;
        }

        /* 进度条样式 */
        .progress-container {
            margin-top: 20px;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 8px;
            border: 1px solid #dee2e6;
        }

        .progress-header {
            display: flex;
            justify-content: space-between;
            margin-bottom: 10px;
            font-size: 0.9em;
            color: #495057;
        }

        .progress-bar {
            width: 100%;
            height: 24px;
            background: #e9ecef;
            border-radius: 12px;
            overflow: hidden;
            position: relative;
        }

        .progress-fill {
            height: 100%;
            background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
            border-radius: 12px;
            transition: width 0.3s ease;
            width: 0%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 0.85em;
            font-weight: 600;
        }

        @keyframes pulse {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.6; }
        }

        .progress-fill.animating {
            animation: pulse 1.5s ease-in-out infinite;
        }

        /* Markdown内容样式 */
        .markdown-content {
            background: white;
            padding: 20px;
            border-radius: 8px;
            line-height: 1.8;
            color: #333;
        }

        .markdown-content h1 {
            color: #667eea;
            font-size: 1.8em;
            margin: 20px 0 15px 0;
            padding-bottom: 10px;
            border-bottom: 2px solid #667eea;
        }

        .markdown-content h2 {
            color: #764ba2;
            font-size: 1.5em;
            margin: 18px 0 12px 0;
            padding-bottom: 8px;
            border-bottom: 1px solid #e9ecef;
        }

        .markdown-content h3 {
            color: #495057;
            font-size: 1.3em;
            margin: 15px 0 10px 0;
        }

        .markdown-content h4 {
            color: #6c757d;
            font-size: 1.1em;
            margin: 12px 0 8px 0;
        }

        .markdown-content p {
            margin: 10px 0;
            text-align: justify;
        }

        .markdown-content ul, .markdown-content ol {
            margin: 10px 0;
            padding-left: 30px;
        }

        .markdown-content li {
            margin: 5px 0;
        }

        .markdown-content code {
            background: #f8f9fa;
            padding: 2px 6px;
            border-radius: 3px;
            font-family: 'Courier New', monospace;
            font-size: 0.9em;
            color: #e83e8c;
        }

        .markdown-content pre {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 6px;
            overflow-x: auto;
            margin: 15px 0;
            border: 1px solid #dee2e6;
        }

        .markdown-content pre code {
            background: none;
            padding: 0;
            color: inherit;
            font-size: 0.9em;
        }

        .markdown-content blockquote {
            border-left: 4px solid #667eea;
            padding-left: 15px;
            margin: 15px 0;
            color: #6c757d;
            font-style: italic;
        }

        .markdown-content table {
            width: 100%;
            border-collapse: collapse;
            margin: 15px 0;
        }

        .markdown-content table th,
        .markdown-content table td {
            border: 1px solid #dee2e6;
            padding: 10px;
            text-align: left;
        }

        .markdown-content table th {
            background: #f8f9fa;
            font-weight: 600;
            color: #495057;
        }

        .markdown-content table tr:hover {
            background: #f8f9fa;
        }

        .markdown-content a {
            color: #667eea;
            text-decoration: none;
        }

        .markdown-content a:hover {
            text-decoration: underline;
        }

        .markdown-content hr {
            border: none;
            border-top: 2px solid #e9ecef;
            margin: 20px 0;
        }

        .markdown-content strong {
            color: #212529;
            font-weight: 600;
        }

        .markdown-content em {
            color: #6c757d;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🔍 代码分析</h1>
            <button class="btn-back" onclick="goBack()">← 返回项目</button>
        </div>

        <!-- 分析配置 -->
        <div class="panel">
            <div class="panel-title">新建分析</div>
            <div id="messageBox" class="message"></div>
            
            <div class="form-group">
                <label>选择AI模型</label>
                <div class="model-buttons" id="modelButtons">
                    <!-- AI模型按钮将在这里动态生成 -->
                </div>
                <div class="help-text">选择用于分析的AI模型</div>
            </div>

            <div class="form-group">
                <label>选择涉及的项目（可多选）</label>
                <div class="project-buttons" id="projectButtons">
                    <!-- 项目按钮将在这里动态生成 -->
                </div>
                <div class="help-text">选择本次需求涉及的代码项目，支持多选</div>
            </div>

            <div class="form-group">
                <label for="testCaseSelect">选择测试用例</label>
                <select id="testCaseSelect">
                    <option value="">加载中...</option>
                </select>
                <div class="help-text">选择用于分析的测试用例</div>
            </div>

            <div class="form-group">
                <label>MR地址（可添加多个）</label>
                <div id="mrInputs">
                    <div class="mr-input-wrapper">
                        <input 
                            type="text" 
                            class="mr-url-input"
                            placeholder="https://gitlab.com/your-org/project/-/merge_requests/123"
                        >
                    </div>
                </div>
                <button class="btn-add-mr" onclick="addMrInput()">+ 添加更多MR</button>
                <div class="help-text">GitLab Merge Request 的完整URL，支持添加多个</div>
            </div>

            <button class="btn btn-primary" onclick="startAnalysis()" id="analyzeBtn">
                🔍 开始分析
            </button>
            
            <!-- 进度条 -->
            <div id="progressContainer" class="progress-container" style="display: none;">
                <div class="progress-header">
                    <span id="progressText">准备中...</span>
                    <span id="progressPercent">0%</span>
                </div>
                <div class="progress-bar">
                    <div id="progressFill" class="progress-fill"></div>
                </div>
            </div>
        </div>

        <!-- 分析结果列表 -->
        <div class="panel">
            <div class="panel-title">分析结果</div>
            <div id="analysisList">
                <div class="loading">
                    <div class="spinner"></div>
                    <p>加载中...</p>
                </div>
            </div>
        </div>
    </div>

    <script>
        const projectId = window.location.pathname.split('/')[2];
        let selectedProjects = []; // 存储选中的项目
        let gitlabProjects = []; // 存储GitLab项目配置
        let selectedProvider = ''; // 存储选中的AI提供商
        let selectedKeyId = ''; // 存储选中的密钥ID
        let aiModels = []; // 存储AI模型列表

        // 页面加载
        window.onload = function() {
            loadAIModels();
            loadGitLabProjects();
            loadTestCases();
            loadAnalyses();
        };

        // 加载AI模型列表
        async function loadAIModels() {
            try {
                const response = await fetch('/api/models');
                if (!response.ok) throw new Error('加载失败');
                
                const data = await response.json();
                if (data.success) {
                    aiModels = data.models || [];
                    renderModelButtons();
                }
            } catch (error) {
                console.error('加载AI模型失败:', error);
            }
        }

        // 渲染AI模型按钮
        function renderModelButtons() {
            const container = document.getElementById('modelButtons');
            
            if (aiModels.length === 0) {
                container.innerHTML = '<p style="color: #999;">暂无可用的AI模型</p>';
                return;
            }
            
            const buttonsHtml = aiModels.map((model, index) => `
                <div class="model-btn" onclick="selectModel('${model.provider}', '${model.key_id || ''}', ${index})" id="model-btn-${index}">
                    <div class="model-name">${getProviderIcon(model.provider)} ${escapeHtml(model.name)}</div>
                    <div class="model-info">${escapeHtml(model.model)}</div>
                    <span class="model-badge">${escapeHtml(model.provider)}</span>
                </div>
            `).join('');
            
            container.innerHTML = buttonsHtml;
            
            // 默认选中第一个
            if (aiModels.length > 0) {
                selectModel(aiModels[0].provider, aiModels[0].key_id || '', 0);
            }
        }

        // 获取提供商图标
        function getProviderIcon(provider) {
            const icons = {
                'doubao': '🤖',
                'deepseek': '🔮'
            };
            return icons[provider] || '🤖';
        }

        // 选择AI模型
        function selectModel(provider, keyId, index) {
            // 移除所有选中状态
            document.querySelectorAll('.model-btn').forEach(btn => {
                btn.classList.remove('selected');
            });
            
            // 添加选中状态
            const btn = document.getElementById(`model-btn-${index}`);
            if (btn) {
                btn.classList.add('selected');
            }
            
            selectedProvider = provider;
            selectedKeyId = keyId;
        }

        // 加载GitLab项目配置
        async function loadGitLabProjects() {
            try {
                const response = await fetch('/api/gitlab/projects');
                if (!response.ok) throw new Error('加载失败');
                
                const data = await response.json();
                if (data.success) {
                    gitlabProjects = data.projects || [];
                    renderProjectButtons();
                }
            } catch (error) {
                console.error('加载GitLab项目失败:', error);
            }
        }

        // 渲染项目按钮
        function renderProjectButtons() {
            const container = document.getElementById('projectButtons');
            
            if (gitlabProjects.length === 0) {
                container.innerHTML = '<p style="color: #999;">暂无配置的项目</p>';
                return;
            }
            
            const buttonsHtml = gitlabProjects.map((project, index) => `
                <div class="project-btn" onclick="toggleProject(${index})" id="project-btn-${index}">
                    <div class="project-btn-name">📦 ${escapeHtml(project.name)}</div>
                    <div class="project-btn-branch">分支: ${escapeHtml(project.default_branch || project.branch || 'test')}</div>
                    <div class="project-btn-repo" title="${escapeHtml(project.repo_url)}">${escapeHtml(project.repo_url.split('/').pop())}</div>
                </div>
            `).join('');
            
            container.innerHTML = buttonsHtml;
        }

        // 切换项目选中状态
        function toggleProject(index) {
            const project = gitlabProjects[index];
            const btn = document.getElementById(`project-btn-${index}`);
            
            const existingIndex = selectedProjects.findIndex(p => p.name === project.name);
            
            if (existingIndex > -1) {
                // 已选中，取消选中
                selectedProjects.splice(existingIndex, 1);
                btn.classList.remove('selected');
            } else {
                // 未选中，添加到选中列表
                selectedProjects.push(project);
                btn.classList.add('selected');
            }
        }

        // 加载测试用例下拉列表
        async function loadTestCases() {
            try {
                const response = await fetch(`/api/project/${projectId}/testcases`);
                if (!response.ok) throw new Error('加载失败');
                
                const testCases = await response.json();
                const select = document.getElementById('testCaseSelect');
                
                if (!testCases || testCases.length === 0) {
                    select.innerHTML = '<option value="">暂无测试用例，请先生成</option>';
                    return;
                }
                
                // 按生成时间倒序排序
                testCases.sort((a, b) => new Date(b.generated_at) - new Date(a.generated_at));
                
                const options = testCases.map(tc => 
                    `<option value="${tc.id}">#${tc.id} - ${tc.title || '测试用例'} (${new Date(tc.created_at || tc.generated_at).toLocaleDateString('zh-CN')})</option>`
                ).join('');
                
                select.innerHTML = '<option value="">请选择...</option>' + options;
                
            } catch (error) {
                document.getElementById('testCaseSelect').innerHTML = 
                    '<option value="">加载失败</option>';
            }
        }

        // 添加MR输入框
        function addMrInput() {
            const container = document.getElementById('mrInputs');
            const wrapper = document.createElement('div');
            wrapper.className = 'mr-input-wrapper';
            wrapper.innerHTML = `
                <input 
                    type="text" 
                    class="mr-url-input"
                    placeholder="https://gitlab.com/your-org/project/-/merge_requests/123"
                >
                <button class="mr-remove-btn" onclick="removeMrInput(this)" title="删除">×</button>
            `;
            container.appendChild(wrapper);
        }

        // 删除MR输入框
        function removeMrInput(btn) {
            const wrapper = btn.parentElement;
            wrapper.remove();
        }

        // 获取所有MR地址
        function getAllMrUrls() {
            const inputs = document.querySelectorAll('.mr-url-input');
            const urls = [];
            inputs.forEach(input => {
                const url = input.value.trim();
                if (url) {
                    urls.push(url);
                }
            });
            return urls;
        }

        // 开始分析
        async function startAnalysis() {
            const testCaseId = document.getElementById('testCaseSelect').value;
            const mrUrls = getAllMrUrls();
            
            if (!selectedProvider) {
                showMessage('请选择AI模型', 'error');
                return;
            }
            
            if (selectedProjects.length === 0) {
                showMessage('请至少选择一个项目', 'error');
                return;
            }
            
            if (!testCaseId) {
                showMessage('请选择测试用例', 'error');
                return;
            }
            
            if (mrUrls.length === 0) {
                showMessage('请至少输入一个MR地址', 'error');
                return;
            }
            
            const btn = document.getElementById('analyzeBtn');
            btn.disabled = true;
            btn.textContent = '分析中...';
            
            // 显示进度条
            showProgress(0, '开始代码分析...');
            
            try {
                // 模拟进度更新
                const progressInterval = simulateAnalysisProgress();
                
                const response = await fetch(`/api/project/${projectId}/analyze`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        ai_provider: selectedProvider,
                        ai_key_id: selectedKeyId,
                        projects: selectedProjects,
                        test_case_id: testCaseId,
                        mr_urls: mrUrls
                    })
                });
                
                clearInterval(progressInterval);
                
                const result = await response.json();
                if (!result.success) throw new Error(result.error || '分析失败');
                
                showProgress(100, '分析完成！');
                showMessage('分析完成！', 'success');
                
                setTimeout(() => {
                    hideProgress();
                    loadAnalyses();
                }, 1500);
                
                // 清空选择
                selectedProjects = [];
                document.querySelectorAll('.project-btn').forEach(btn => {
                    btn.classList.remove('selected');
                });
                
                // 清空MR输入框
                const mrInputs = document.querySelectorAll('.mr-url-input');
                mrInputs.forEach(input => input.value = '');
                
            } catch (error) {
                hideProgress();
                showMessage('分析失败: ' + error.message, 'error');
            } finally {
                btn.disabled = false;
                btn.textContent = '🔍 开始分析';
            }
        }

        // 显示进度条
        function showProgress(percent, text) {
            const container = document.getElementById('progressContainer');
            const fill = document.getElementById('progressFill');
            const progressText = document.getElementById('progressText');
            const progressPercent = document.getElementById('progressPercent');
            
            container.style.display = 'block';
            fill.style.width = percent + '%';
            progressText.textContent = text;
            progressPercent.textContent = percent + '%';
            
            if (percent < 100) {
                fill.classList.add('animating');
            } else {
                fill.classList.remove('animating');
            }
        }

        // 隐藏进度条
        function hideProgress() {
            const container = document.getElementById('progressContainer');
            container.style.display = 'none';
        }

        // 模拟分析进度更新
        function simulateAnalysisProgress() {
            const stages = [
                { percent: 15, text: '正在拉取项目代码...' },
                { percent: 30, text: '正在获取MR变更内容...' },
                { percent: 50, text: '正在分析代码变更...' },
                { percent: 70, text: 'AI正在进行深度分析...' },
                { percent: 85, text: '正在生成分析报告...' },
                { percent: 95, text: '即将完成...' }
            ];
            let stageIndex = 0;
            
            const interval = setInterval(() => {
                if (stageIndex < stages.length) {
                    const stage = stages[stageIndex];
                    showProgress(stage.percent, stage.text);
                    stageIndex++;
                }
            }, 3000); // 每3秒更新一次
            
            return interval;
        }

        // 加载分析结果列表
        async function loadAnalyses() {
            try {
                const response = await fetch(`/api/project/${projectId}/analyses`);
                if (!response.ok) throw new Error('加载失败');
                
                const analyses = await response.json();
                renderAnalyses(analyses);
            } catch (error) {
                document.getElementById('analysisList').innerHTML = `
                    <div class="empty-state">
                        <div class="empty-state-icon">🔍</div>
                        <p>暂无分析结果</p>
                    </div>
                `;
            }
        }

        // 渲染分析结果列表
        function renderAnalyses(analyses) {
            const container = document.getElementById('analysisList');
            
            if (!analyses || analyses.length === 0) {
                container.innerHTML = `
                    <div class="empty-state">
                        <div class="empty-state-icon">🔍</div>
                        <p>暂无分析结果</p>
                        <p style="margin-top: 10px; font-size: 0.9em;">完成配置后点击"开始分析"</p>
                    </div>
                `;
                return;
            }
            
            // 按分析时间倒序排序
            analyses.sort((a, b) => new Date(b.started_at) - new Date(a.started_at));
            
            const html = analyses.map(analysis => {
                // 渲染Markdown内容
                const markdownHtml = renderMarkdown(analysis.analysis_result || '分析结果为空');
                
                return `
                    <div class="analysis-item">
                        <div class="analysis-header">
                            <div class="analysis-title">📊 代码分析报告</div>
                        </div>
                        <div class="analysis-meta">
                            <strong>MR地址:</strong> ${escapeHtml(analysis.mr_url)}<br>
                            <strong>分析时间:</strong> ${new Date(analysis.started_at).toLocaleString('zh-CN')}<br>
                            ${analysis.project_name ? `<strong>项目:</strong> ${escapeHtml(analysis.project_name)}<br>` : ''}
                            ${analysis.ai_provider ? `<strong>AI模型:</strong> ${escapeHtml(analysis.ai_provider)}<br>` : ''}
                        </div>
                        <div class="analysis-content markdown-content">
                            ${markdownHtml}
                        </div>
                    </div>
                `;
            }).join('');
            
            container.innerHTML = `<div class="analysis-list">${html}</div>`;
            
            // 高亮代码块
            document.querySelectorAll('pre code').forEach((block) => {
                hljs.highlightElement(block);
            });
        }

        // 渲染Markdown为HTML
        function renderMarkdown(markdownText) {
            if (!markdownText) return '<p>无内容</p>';
            
            // 配置marked选项
            marked.setOptions({
                breaks: true,
                gfm: true,
                headerIds: true,
                mangle: false
            });
            
            try {
                return marked.parse(markdownText);
            } catch (error) {
                console.error('Markdown渲染失败:', error);
                return `<pre>${escapeHtml(markdownText)}</pre>`;
            }
        }

        // 返回
        function goBack() {
            window.location.href = `/project/${projectId}`;
        }

        // 显示消息
        function showMessage(message, type) {
            const box = document.getElementById('messageBox');
            box.textContent = message;
            box.className = `message ${type} show`;
            
            setTimeout(() => {
                box.classList.remove('show');
            }, type === 'success' ? 3000 : 5000);
        }

        // 辅助函数
        function escapeHtml(text) {
            if (!text) return '';
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }
    </script>
</body>
</html>

